package com.example.services;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;

import com.example.ShoppingCartApiApplication;
import com.example.exceptions.CustomerNotFoundException;
import com.example.models.Customer;
import com.example.repositories.CustomerRepository;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ShoppingCartApiApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=9090"})
public class CustomerServiceIT {
	@Autowired
    private CustomerRepository customerRepository;
	
	@Autowired
    private CustomerService customerService;
	
	@Autowired
    private WebApplicationContext webApplicationContext;
	
	ArrayList<Customer> customers= new ArrayList<Customer>();
	Customer customer,customer2;

	
	@Before
    public void setup() throws Exception {

        this.customerRepository.deleteAll();
        
        customer = customerRepository.save(new Customer("cid", "customer", "customerFirst", "customerLast"));
		customer2= customerRepository.save(new Customer("cid2", "customer2", "customer2First", "customer2Last"));
		customers.add(customer);
        customers.add(customer2);
    }
	
	@Test(expected = CustomerNotFoundException.class) 
	public void customerNotFound() throws Exception{
		customerService.find("123");
	}
    
    @Test
    public void readSingleCustomer() throws Exception {
    	Customer result = customerService.find(customer.getId());
    	assertEquals(customer.getFirstName(), result.getFirstName());
    	assertEquals(customer.getLastName(), result.getLastName());
    	assertEquals(customer.getUsername(), result.getUsername());
    }
    
    @Test
    public void readAllCustomers() throws Exception {
    	Collection<Customer> result = customerService.findAll();
		Iterator<Customer> iterator = result.iterator();
		int index=0;
		while(iterator.hasNext()){
			Customer next = iterator.next();
			assertEquals(customers.get(index).getFirstName(), next.getFirstName());
			assertEquals(customers.get(index).getLastName(), next.getLastName());
			assertEquals(customers.get(index).getLastName(), next.getLastName());
			index++;
		}
    }
}
